﻿using BoldSeas.Framework.Common.Helper;
using BoldSeas.Framework.Log;
using DAl;
using FCA.Common;
using FCA.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;

namespace HWCOMM.ASHX
{
    /// <summary>
    /// ConductModel 的摘要说明
    /// </summary>
    public class ConductModel : IHttpHandler
    {
        #region 私有变量

        #endregion

        #region 程序入口
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string type = context.Request["type"];
            switch (type.ToLower())
            {

                case "import":
                    ImportEX(context);//导入EX
                    break;
                case "kouling":
                    verifyClient(context);
                    break;
                default:
                    Log4net.Info("【获取ajax提交类型type=】" + type);
                    break;
            }
        }
        #endregion

        #region 查询相关


        #region 验证口令
        private void verifyClient(HttpContext context)
        {
            string kouLing = context.Request["data"];
            if (kouLing == "123qwe")
            {
                context.Response.Write("ok");
                return;
            }
            else
            {
                context.Response.Write("on");
                return;
            }
        }
        #endregion
        #endregion

        #region 更改相关

        #region 导入EX
        /// <summary>
        /// 导入EX
        /// </summary>
        /// <param name="context"></param>
        private static void ImportEX(HttpContext context)
        {
            try
            {
                HttpPostedFile EX = context.Request.Files["file"];
                string paperFile = string.Empty;
                //获取扩展名
                string files = Path.GetExtension(EX.FileName);
                string filename = EX.FileName.Replace("\\", "#");
                //对路径字符串进行剪切截取
                string[] one = filename.Split('#');
                //获取数组中最后一个，即文件名
                string two = one[one.Length - 1];
                //再对文件名进行截取，以取得后缀名
                string[] three = two.Split('.');
                //获取截取的最后一个字符串，即为后缀名
                string Name = "_" + three[0] + files;
                string FileName = DateTime.Now.ToString();
                FileName = FileName.Replace("//", "").Replace(".", "").Replace(" ", "").Replace("/", "").Replace(":", "") + Name;
                string MapPath = context.Server.MapPath("..//EX//");
                if (!Directory.Exists(MapPath))
                {
                    Directory.CreateDirectory(MapPath);
                }
                string phyPath = MapPath + FileName;
                EX.SaveAs(phyPath);
                if (!string.IsNullOrEmpty(phyPath))
                {
                    DataTable table = ExcelRender.RenderFromExcel(phyPath);
                    if (table == null || table.Rows.Count <= 0)
                    {
                        return;
                    }
                    List<FCA_DealerUser> UserList = UserDal.GetDealerUser();
                    List<FCA_DealerUser> EXUserList = ModelConvertHelper<FCA_DealerUser>.ConvertToModelList(table);
                    FCA_DealerUser userModel = new FCA_DealerUser();
                    string sqlstr = string.Empty;
                    int successCount = 0, failureCount = 0, helisCount = 0;
                    StringBuilder successInfo = new StringBuilder();
                    StringBuilder failureInfo = new StringBuilder();
                    StringBuilder helisInfo = new StringBuilder();
                    foreach (var ex in EXUserList)
                    {
                        userModel = UserList.Where(m => m.DealerCode == ex.DealerCode && m.DealerUserID == ex.DealerUserID).FirstOrDefault();
                        if (userModel == null || string.IsNullOrEmpty(userModel.DealerUserID))
                        {
                            userModel = UserList.Where(m => m.DealerCode == ex.DealerCode && m.UserRole == "2" && ex.UserRole == "2").FirstOrDefault();
                            if (userModel == null)
                            {
                                sqlstr = string.Format(@" Insert into DealerUser(DealerUserID, DealerCode, LoginName, PassWord, UserRole, DMSRoleID, DMSRoleName, UserName, UserPhone, IsShowExplain, Email, IsDCCView, CreateDate, UserStatus) values('{0}','{1}','{2}','{3}',{4},'{5}','{6}','{7}','{8}',{9},'{10}','{11}','{12}','{13}') 
", ex.DealerUserID, ex.DealerCode, ex.LoginName, ex.PassWord, ex.UserRole, ex.DMSRoleID, ex.DMSRoleName, ex.UserName, ex.UserPhone, 1, ex.Email, ex.IsDCCView, DateTime.Now.ToString(), "12101001");
                                if (UserDal.InsertUser(sqlstr) == "Success")
                                {
                                    UserDal.InsertUserTemp(sqlstr);
                                    successCount++;
                                    successInfo.Append(string.Format("DealerUserID={0},DealerCode={1}\\r\\n", ex.DealerUserID, ex.DealerCode));
                                }
                                else
                                {
                                    failureCount++;
                                    failureInfo.Append(string.Format("DealerUserID={0},DealerCode={1}\\r\\n", ex.DealerUserID, ex.DealerCode));
                                }
                            }
                            else
                            {
                                helisCount++;
                                helisInfo.Append(string.Format("UserRole={0},DealerCode={1}\\r\\n", ex.UserRole, ex.DealerCode));
                            }
                        }
                        else
                        {
                            helisCount++;
                            sqlstr = string.Format(@" Update DealerUser set LoginName='{0}',PassWord='{1}',UserRole='{2}',DMSRoleID='{3}',DMSRoleName='{4}',UserName='{5}',UserPhone='{6}',Email='{7}',IsDCCView='{8}' where DealerUserID='{9}' and DealerCode='{10}'
", ex.LoginName,ex.PassWord,ex.UserRole,ex.DMSRoleID,ex.DMSRoleName,ex.UserName,ex.UserPhone,ex.Email,ex.IsDCCView,ex.DealerUserID,ex.DealerCode);
                            UserDal.UpUser(sqlstr) ;
                            UserDal.UpUserTemp(sqlstr);
                            helisInfo.Append(string.Format("DealerUserID={0},DealerCode={1}\\r\\n", ex.DealerUserID, ex.DealerCode));
                        }
                    }
                    string js = "{\"count\":" + EXUserList.Count + ",\"successCount\":" + successCount + ",\"failureCount\":" + failureCount + ",\"helisCount\":" + helisCount + ",\"successInfo\":\"" + successInfo.ToString() + "\",\"failureInfo\":\"" + failureInfo.ToString() + "\",\"helisInfo\":\"" + helisInfo.ToString() + "\"}";
                    context.Response.Write(js);
                    return;//此处不能使用context.Response.End，因为End和Redirect同时使用会异常
                }
                else
                {
                    Log4net.Info("导入EX路径为空 filepath=" + phyPath);
                    context.Response.Write("no");
                    return;
                }
            }
            catch (Exception ex)
            {
                Log4net.Error(MethodBase.GetCurrentMethod(), ex);
                context.Response.Write("error");
                return;
            }
        }
        #endregion

        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}